package com.kancy.jemeter.functions;

import com.kancy.jemeter.util.Base64Util;
import com.kancy.jemeter.util.MessageUtil;
import org.apache.commons.io.FileUtils;
import org.apache.jmeter.functions.InvalidVariableException;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * @author kancy
 * @date 2019/6/29 17:17
 */
public class Base64Function extends JemeterAbstractFunction {

	public Base64Function() {
		super(0,3);
	}

	@Override
	public String execute(SampleResult sampleResult, Sampler sampler) throws InvalidVariableException {
		String data = getParameter(0);

		byte[] bytes = null;
		File file = new File(data);
		if(file.exists() && file.isFile()){
			try {
				bytes = FileUtils.readFileToByteArray(file);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			bytes = data.getBytes();
		}
		String type = getParameter(1, "1");

		String result = "";
		if("1".equals(type)){
			result = Base64Util.encodeBytes(bytes);
		}else{
			result = Base64Util.decode(new String(bytes));
		}
		return setJMeterVariable(2, result);
	}


	private static final List<String> argumentDesclist = new LinkedList();

	static {
		argumentDesclist.add(MessageUtil.getResString("__base64.content.message"));
		argumentDesclist.add(MessageUtil.getResString("__base64.type.message"));
		argumentDesclist.add(MessageUtil.getResString("varname.message"));
	}
	@Override
	public List<String> getArgumentDesc() {
		return argumentDesclist;
	}

}
